<?php



namespace App\Model;

use App\Util\ComUtil;
use App\Util\SandPayUtil;
use App\Util\YzhUtil;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 提现申请
 */
class Withdraw extends Model
{
    protected $table = 'user_withdraw';
    protected $fillable = ['status', 'yzh_order_id', 'withdraw_way', 'out_trans_id', 'account_type'];

    //待审核
    const STATUS_ING = 0;
    //审核通过
    const STATUS_OK = 1;
    //审核不通过
    const STATUS_FAIL = 2;
    //云账户提现异常
    const STATUS_YZH_ERR = 3;
    //状态
    const STATUS = [
        self::STATUS_ING => '待处理',
        self::STATUS_OK => '已提现',
        self::STATUS_FAIL => '不允许提现',
        self::STATUS_YZH_ERR => '提现异常'
    ];

    const ACCOUNT_TYPE = [
        0 => '支付宝',
        1 => '银行卡',
        2 => '微信零钱',
        -1 => '未知'
    ];

    const SEC_IN_ARRIVE = [
        0 => '不是秒到账',
        1 => '秒到账',
    ];

    const WITHDRAW_WAY = [
        'yzh' => '云账户',
        'wechat' => '微信商户号',
        'alipay_b' => '支付宝商户',
        'alipay' => '支付宝个人',
        'sand' => '杉德',
        'wechat_p' => '微信零钱'
    ];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    public function personalProfile()
    {
        return $this->belongsTo(UserProfilePersonal::class, 'user_id', 'user_id');
    }

    public function socialItem()
    {
        return $this->belongsTo(SocialAccount::class, 'user_id', 'user_id');
    }

    /**
     * 通知云账户下单
     */
    static function doYzhOrder($withdrawRecord = null)
    {
        if (!$withdrawRecord) return false;
        $userId = $withdrawRecord['user_id'];
        $payRmb = $withdrawRecord['withdraw_rmb'];
        $bindInfo = UserProfilePersonal::getBindInfo($userId, '');
        if (!$bindInfo) return ['ret' => -1, 'message' => '提现信息不存在，或者没有认证通过！'];
        $orderInfo = [
            'pay_money' => $payRmb,
            'id_card' => $bindInfo['id_card'],
            'real_name' => $bindInfo['real_name'],
            'card_no' => $bindInfo['card_no'],
            'notify_url' => config('yzh.notify_url'),
            'order_id' => $orderId = ComUtil::buildOrderId($userId),
        ];
        //是否支付宝
        $bindAliAccount = UserProfilePersonal::BIND_TYPE_ALI == $bindInfo['type'];

        //更新云账户订单ID
        Withdraw::where('id', $withdrawRecord['id'])->update([
            'yzh_order_id' => $orderId,
            //银行卡
            'account_type' => $bindAliAccount ? 0 : 1,
        ]);

        if ($bindAliAccount) {
            $result = YzhUtil::orderAlipay($orderInfo);
        } else {
            $result = YzhUtil::orderBank($orderInfo);
        }
        if (isset($result['code']) && $result['code'] == '0000') {
            return ['ret' => 0, 'message' => '已成功提交提现请求', 'bind_type' => $bindInfo['type']];
        }
        return ['ret' => -1, 'message' => "{$result['message']}; ErrCode:{$result['code']}", 'bind_type' => $bindInfo['type']];
    }

    /**
     * 通知杉德下单
     */
    static function doSandOrder($withdrawRecord = null)
    {
        if (!$withdrawRecord) return false;
        $userId = $withdrawRecord['user_id'];
        $payRmb = $withdrawRecord['withdraw_rmb'];
        $bindInfo = UserProfilePersonal::getBindInfo($userId, 'bank');
        if (!$bindInfo) return ['ret' => -1, 'message' => '提现信息不存在，或者没有认证通过！'];
        $orderInfo = [
            'pay_money' => $payRmb * 100,
            'real_name' => $bindInfo['real_name'],
            'card_no' => $bindInfo['card_no'],
            'order_id' => $orderId = ComUtil::buildSandOrderId($userId),
        ];
        //杉德下单
        $result = SandPayUtil::agentPay($orderInfo);
        if (isset($result['respCode']) && $result['respCode'] == '0000') {
            Withdraw::where('id', $withdrawRecord['id'])->update([
                'yzh_order_id' => $orderId,
                'status' => Withdraw::STATUS_OK,
                'withdraw_way' => 'sand'
            ]);
            return ['ret' => 0, 'message' => '已成功提交提现请求'];
        } else {
            $yzhDetail = json_encode([
                'status' => $result['respCode'] ?? '-1',
                'message' => '',
                'detail' => $result['respDesc'] ?? '未知错误',
            ]);
            Withdraw::where('id', $withdrawRecord['id'])->update([
                'yzh_order_id' => $orderId,
                'yzh_detail' => $yzhDetail,
                'status' => Withdraw::STATUS_YZH_ERR,
                'withdraw_way' => 'sand',
                //银行卡
                'account_type' => 1
            ]);
            return ['ret' => -1, 'message' => "{$result['respDesc']}; ErrCode:{$result['respCode']}"];
        }
    }

    /**
     * 待打款的金币数
     */
    static function getUnPay()
    {
        $where = ['status' => self::STATUS_ING];
        $data = self::where($where)->select(DB::raw('SUM(withdraw_coin) as coin'))->first();
        return $data ? $data->coin : 0;
    }

    /**
     * 待打款的金币数
     */
    static function getPay()
    {
        $where = ['status' => self::STATUS_OK];
        $data = self::where($where)->select(DB::raw('SUM(withdraw_coin) as coin'))->first();
        return $data ? $data->coin : 0;
    }

    static function getWithdrawWay($type = '')
    {
        return self::WITHDRAW_WAY[$type] ?? '未知';
    }

    static function getAccountType($type = '')
    {
        return self::ACCOUNT_TYPE[$type] ?? '未知';
    }
}
